package com.neu.question.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.question.beans.PageVO;
import com.neu.question.common.utils.DateUtil;
import com.neu.question.common.utils.UUIDUtil;
import com.neu.question.domain.EndUser;
import com.neu.question.domain.EndUserInfo;
import com.neu.question.domain.ProjectInfo;
import com.neu.question.domain.UserInfo;
import com.neu.question.form.EndUserForm;
import com.neu.question.form.SearchForm;
import com.neu.question.mapper.ProjectInfoMapper;
import com.neu.question.mapper.UserInfoMapper;
import com.neu.question.service.EndUserInfoService;
import com.neu.question.mapper.EndUserInfoMapper;
import com.neu.question.service.ProjectInfoService;
import com.neu.question.service.UserInfoService;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author DELL
* @description 针对表【end_user_info(用户特有特征表-关联总统人员表)】的数据库操作Service实现
* @createDate 2022-11-04 16:09:18
*/
@Service
public class EndUserInfoServiceImpl extends ServiceImpl<EndUserInfoMapper, EndUserInfo>
    implements EndUserInfoService{

    @Autowired
    private EndUserInfoMapper endUserInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private EndUserInfoService endUserInfoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ProjectInfoMapper projectEntityMapper;

    @Override
    public PageVO  list(Integer page, Integer size, String name) {
        Page<EndUserInfo> endUserInfoPage = new Page<>(page,size);
        QueryWrapper<EndUserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenants_id", name);
        Page<EndUserInfo> endUserInfoPage1 = this.endUserInfoMapper.selectPage(endUserInfoPage, queryWrapper);
        PageVO pageVO = new PageVO();
        pageVO.setTotal(endUserInfoPage1.getTotal());

        List<EndUserInfo> records = endUserInfoPage1.getRecords();
        List<EndUser> endUsers = new ArrayList<>();
        EndUser endUser = null;
        UserInfo userInfo = null;
        for (EndUserInfo re: records
             ) {
            endUser = new EndUser();
            userInfo = userInfoMapper.selectById(re.getUserId());
            endUser = endUser.create(re, userInfo.getUsername(), userInfo.getPhoneNum(), userInfo.getStatus());
            endUsers.add(endUser);
        }
        pageVO.setData(endUsers);
        return pageVO;
    }

    @Override
    public PageVO search(SearchForm searchForm) {
        // 模糊查询加分页
        Page<EndUserInfo> endUserInfoPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<UserInfo> userInfoPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<EndUserInfo> endUserInfoPage1 = null;
        Page<UserInfo> userInfoPage1 = null;
        PageVO pageVO = new PageVO();

        List<EndUser> endUsers = new ArrayList<>();
        if (searchForm.getValue().equals("")) {
            endUserInfoPage1 = this.endUserInfoMapper.selectPage(endUserInfoPage, null);
        } else {
            // 判断查询key
            if (searchForm.getKey().equals("username")) {
                QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.like(searchForm.getKey(), searchForm.getValue());
                List<UserInfo> list = userInfoService.list(queryWrapper);
                queryWrapper.eq("created_by", searchForm.getTename());



//                System.out.println( searchForm.getTename());
                userInfoPage1 = userInfoMapper.selectPage(userInfoPage, queryWrapper);
                pageVO.setTotal(userInfoPage1.getTotal());
                List<UserInfo> records1 = userInfoPage1.getRecords();
                for (UserInfo u: records1
                     ) {
                    EndUser user = new EndUser();
                    QueryWrapper<EndUserInfo> endUserInfoQueryWrapper = new QueryWrapper<>();
                    endUserInfoQueryWrapper.eq("user_id", u.getId());
//                    System.out.println(u.getId());

//                    System.out.println(searchForm.getTename());
//                    endUserInfoQueryWrapper.eq("tenants_id", searchForm.getTename());


                    //出问题了  ！！！ 要全部加进去或者用另一个分页
                    EndUserInfo one = endUserInfoService.getOne(endUserInfoQueryWrapper);
                    if (one != null) {
                        user = user.create(one, u.getUsername(), u.getPhoneNum(), u.getStatus());
                        endUsers.add(user);
                    }

                }

            }else{
                QueryWrapper<EndUserInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.like(searchForm.getKey(), searchForm.getValue());
                queryWrapper.eq("tenants_id", searchForm.getTename());
                endUserInfoPage1 = this.endUserInfoMapper.selectPage(endUserInfoPage, queryWrapper);
                pageVO.setTotal(endUserInfoPage1.getTotal());
                List<EndUserInfo> records = endUserInfoPage1.getRecords();

                EndUser endUser = null;
                UserInfo userInfo = null;
                for (EndUserInfo re: records
                ) {
                    endUser = new EndUser();
                    userInfo = userInfoMapper.selectById(re.getUserId());
                    endUser = endUser.create(re, userInfo.getUsername(), userInfo.getPhoneNum(), userInfo.getStatus());
                    endUsers.add(endUser);
                }

            }

        }


        pageVO.setData(endUsers);


        return pageVO;
    }

    @Override
    public int save(EndUserForm endUserForm) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        if (endUserForm.getUsername() != null) {
            queryWrapper.eq("username", endUserForm.getUsername());
            if (userInfoService.getOne(queryWrapper) != null) {
                //用户名已经存在
                return 3;
            }

        }
        if (endUserForm.getPhoneNum() != null) {

            QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("phone_num", endUserForm.getPhoneNum());
            UserInfo one = userInfoService.getOne(queryWrapper1);
//            System.out.println(one.getPhoneNum());
            if (userInfoService.getOne(queryWrapper1) != null) {
                //电话号已经存在
                return 4;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("username", endUserForm.getUsername());
        map.put("phoneNum", endUserForm.getPhoneNum());
        map.put("password", endUserForm.getPassword());
        map.put("roleId", "2");
        String id = UUIDUtil.getOneUUID();
        map.put("id", id);
        //创建时间
        Date date = DateUtil.getCreateTime();
        map.put("creationDate", date);
        map.put("lastUpdateDate", date);
        //创建人
        //String createduserid = map.get("id").toString();
        //Map<String,Object> querymap = new JSONObject();
        //querymap.put("id",createduserid);
        // Map<String,Object> queryresult = userEntityMapper.queryUserById(querymap);
        //String user = queryresult.get("username").toString();
        String user = endUserForm.getOpusername();

        map.put("createdBy", user);
        map.put("lastUpdatedBy", user);
        //前台传入的时间戳转换
//        String startTimeStr = endUserForm.getStartTime();
//        String endTimeStr = endUserForm.getStopTime();
//        Date startTime = DateUtil.getMyTime(startTimeStr);
//        Date endTime = DateUtil.getMyTime(endTimeStr);
//        System.out.println("222222");
//        System.out.println(endTime);
//        map.put("startTime", startTime);
//        map.put("stopTime", endTime);
        map.put("startTime", endUserForm.getStartTime());
        map.put("stopTime", endUserForm.getStopTime());


        int result = userInfoMapper.addUserInfo(map);
        UserInfo userInfo = userInfoMapper.selectById(id);
        Date date1 = new Date();
        if (endUserForm.getStartTime().after(date1)  || endUserForm.getStopTime().before(date1)) {
            userInfo.setStatus("0");
            userInfoService.saveOrUpdate(userInfo);
        }

        //租户才能创建用户
        if (endUserForm.getTenantsId() == null) {
            //没有传入租户ID
            //成功存入user_info  但是没有成功存入end_user_info
//            System.out.println(endUserForm.getTenantsId());
            return 2;
        } else {
            EndUserInfo endUserInfo = new EndUserInfo();
            endUserInfo.setUserId(id);
            endUserInfo.setTenantsId(endUserForm.getTenantsId());
            endUserInfo.setQuestionnaireNum(endUserForm.getQuestionnaireNum());
            endUserInfo.setUseProject("0");
            endUserInfo.setUseQuestionnaire("0");
            endUserInfo.setUseAnswer("0");
            endUserInfo.setUseGroup("0");
            if (endUserInfoService.save(endUserInfo)) {
                //如果成功存入不操作
                return result;
            } else {
                //成功存入user_info  但是没有成功存入end_user_info
                return 5;
            }
        }



    }

    @Override
    public int update(EndUserForm endUserForm, boolean change) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

//        UserInfo one = userInfoService.getOne(queryWrapper);
        List<UserInfo> userInfoList = userInfoService.list(queryWrapper);
        QueryWrapper<EndUserInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", endUserForm.getId());

        //被修改的用户
        EndUserInfo one = endUserInfoService.getOne(queryWrapper1);
        String oldName = userInfoService.getById(one.getUserId()).getUsername();
        String oldPhone = userInfoService.getById(one.getUserId()).getPhoneNum();
        queryWrapper.eq("username", oldName);

        //被修改的用户
        UserInfo one1 = userInfoService.getOne(queryWrapper);

        //判断用户名
        if (!oldName.equals(endUserForm.getUsername())) {
            queryWrapper.clear();
            queryWrapper.eq("username", endUserForm.getUsername());
            //如果有重名
            if (userInfoService.getOne(queryWrapper) != null) {
                //重名
                return 3;
            }
            one1.setUsername(endUserForm.getUsername());

        }
        if (!oldPhone.equals(endUserForm.getPhoneNum())) {
            queryWrapper.clear();
            queryWrapper.eq("phone_num", endUserForm.getPhoneNum());
            if (userInfoService.getOne(queryWrapper) != null) {
                //重复电话号
                return 4;
            }
            one1.setPhoneNum(endUserForm.getPhoneNum());
        }
        one1.setPassword(endUserForm.getPassword());
        one1.setStopTime(endUserForm.getStopTime());
        if (change) {
            one1.setStatus("0");
        }else {
            one1.setStatus("1");
        }
        if (! userInfoService.saveOrUpdate(one1)) {
            //user存储失败
            return 5;
        }

        one.setQuestionnaireNum(endUserForm.getQuestionnaireNum());
        if (! endUserInfoService.saveOrUpdate(one)) {
            //enduser  false
            return 6;
        }


        return 1;
    }

    @Override
    public int delete(String id) {
        EndUserInfo byId = endUserInfoService.getById(id);
        UserInfo byId1 = userInfoService.getById(byId.getUserId());

        ProjectInfo projectEntity = new ProjectInfo();
        projectEntity.setUserId(byId.getUserId());
        int k = projectEntityMapper.queryExistProjectByUser(projectEntity);
//        System.out.println("0000  " + k);
        if (k != 0) {
            //存在项目 不能删除
//            System.out.println("11");
            return 4;
        } else {
            int i = endUserInfoMapper.deleteById(id);
            if (!(i == 1)) {
                //endUser 删除失败
                return 3;
            }
            int i1 = userInfoMapper.deleteById(byId1.getId());
            if (!(i1 == 1)) {
                //User 删除失败
                return 2;
            }
        }

        return 1;
    }

    @Override
    public void create() {
        List<UserInfo> list = userInfoService.list();
        Date date = new Date();
        for (UserInfo u: list
             ) {
            if (u.getRoleId().equals("2")) {
                if (u.getStopTime().after(date) && u.getStartTime().before(date)) {
                    u.setStatus("1");
                } else {
                    u.setStatus("0");
                }
                userInfoService.saveOrUpdate(u);
            }

        }

//        return false;
    }
}




